// 深拷贝

const obj = {
  age: 20,
  name: 'xxx',
  address: {
    city: 'beijing'
  },
  arr: [1,2,3]
}

const obj1 = obj
obj1.address.city = 'shanghai'
console.log(obj1.address.city)

function deepClone(obj = {}){
  if (typeof obj !== 'object' || obj == null){
    // obj 是 null 或者不是数组和对象，直接返回参数自己
    return obj
  }

  // 初始化返回结果
  let result
  if (obj instanceof Array){
    result = []
  }else{
    result = {}
  }

  for (let key in obj){
      // 保证 key 不是原型的属性
    if (obj.hasOwnProperty(key)){
      // 递归
      result[key] = deepClone(obj[key])
    }
  }

  // 返回
  return result
}

let deep = deepClone(obj)
deep.address.city = 'shantou'
console.log(obj)
console.log(deep)
